import http from 'http';
import https from 'https';
import fs, { stat } from 'fs';
import Koa from 'koa';
import cors from '@koa/cors';
import serve from 'koa-static';
// import logger from 'koa-logger';
import * as FileStreamRotator  from 'file-stream-rotator';
import koaMorgan from 'koa-morgan';
// import Router from 'koa-router';
import router from './router/index'
// const router = new Router();
const app = new Koa();
app.use(serve(`${process.cwd()}/public`,{
    // index:'/index.html',
    // gzip:true
}));

app.use(cors(
    /**
 * CORS middleware
 *
 * @param {Object} [options]
 *  - {String|Function(ctx)} origin `Access-Control-Allow-Origin`, default is '*'
 *    If `credentials` set and return `true, the `origin` default value will set to the request `Origin` header
 *  - {String|Array} allowMethods `Access-Control-Allow-Methods`, default is 'GET,HEAD,PUT,POST,DELETE,PATCH'
 *  - {String|Array} exposeHeaders `Access-Control-Expose-Headers`
 *  - {String|Array} allowHeaders `Access-Control-Allow-Headers`
 *  - {String|Number} maxAge `Access-Control-Max-Age` in seconds
 *  - {Boolean|Function(ctx)} credentials `Access-Control-Allow-Credentials`, default is false.
 *  - {Boolean} keepHeadersOnError Add set headers to `err.header` if an error is thrown
 *  - {Boolean} secureContext `Cross-Origin-Opener-Policy` & `Cross-Origin-Embedder-Policy` headers.', default is false
 *  - {Boolean} privateNetworkAccess handle `Access-Control-Request-Private-Network` request by return `Access-Control-Allow-Private-Network`, default to false
 * @return {Function} cors middleware
 * @api public
 */
{
    origin(ctx:Koa.Context) {
    return ctx.get('Origin') || '*';
    },
}
));
// const logStream = fs.createWriteStream('../logger/logger.log', { flags: 'a' });
// const myConsole = new console.Console(logStream);
// app.use(logger({
//     immediate:true,
//     console: myConsole
// }));
const logStream = FileStreamRotator.getStream({
date_format: 'YYYYMMDD',
filename: `${process.cwd()}/logger/access-%DATE%.log`,
frequency: 'daily',
verbose: false
});

// 使用koa-morgan中间件记录日志
app.use(koaMorgan('combined', {
stream: logStream
}));

app.use(async (ctx:Koa.Context,next:Koa.Next)=>{
    try{
        await next();
        if(ctx.status===404){
            ctx.body = "404"
        }
    } catch(err){
        console.log(err)
    }
    // else{
    //     throw err;
    // }
})
// app.use(async function(ctx:Koa.Context) {
//     ctx.body ="Hello Koaddddaaaa";
// });
app.use(router.routes())
app.use(router.allowedMethods())

// app.listen(3000,function(){
//     console.log("OKddd")
// })

http.createServer(app.callback()).listen(3000).setTimeout(1000);
https.createServer({
    key:fs.readFileSync('./openssl/server.key',"utf8"),
    cert: fs.readFileSync('./openssl/server.cert',"utf8")
}, app.callback()).listen(443);
// https.createServer(app.callback()).listen(3001);